using Aurora.TaskScheduler.Abstractions;
using Aurora.TaskScheduler.Abstractions.BaseModel;
using Aurora.TaskScheduler.Abstractions.Message;
using Aurora.TaskScheduler.Extension.Internel;
using Newtonsoft.Json;

namespace Aurora.TaskScheduler.Extension;

/// <summary>
/// 任务工具类
/// </summary>
public class TaskJobUtil
{
    private readonly ITaskHandler _taskHandler;

    public TaskJobUtil(ITaskHandler taskHandler)
    {
        _taskHandler = taskHandler;
    }

    /// <summary>
    /// 执行任务 时间大概0.1秒
    /// </summary>
    /// <param name="jobType"></param>
    public void InvokeLater(Type jobType)
    {
        InvokeLater(jobType, "", 0.1);
    }

    /// <summary>
    /// 执行任务 时间大概0.1秒
    /// </summary>
    /// <param name="jobType"></param>
    /// <param name="parameter"></param>
    public void InvokeLater(Type jobType, object parameter)
    {
        string val = string.Empty;
        if (parameter is string)
            val = parameter as string;
        else
        {
            if (parameter.GetType().IsValueType)
            {
                val = parameter?.ToString() ?? "";
            }
            else
                val = JsonConvert.SerializeObject(parameter);
        }

        InvokeLater(jobType, val, 0.1);
    }

    /// <summary>
    /// 执行任务 时间大概0.1秒
    /// </summary>
    /// <param name="jobType"></param>
    /// <param name="parameter"></param>
    /// <param name="delay">单位秒 可小数</param>
    public void InvokeLater(Type jobType, string parameter, double delay)
    {
        
        var makeGenericType = jobType.FindInterfacesThatClose(typeof(ITaskJob<>)).FirstOrDefault();
        if (makeGenericType == null)
            return;
        var genericArgument = makeGenericType.GetGenericArguments()[0];
        AppTask task = new()
        {
            TaskName = jobType.FullName + "-" + Guid.NewGuid().ToString().Replace("-", ""),
            GroupName = "BACKGROUNDTASK",
            DllClassName = jobType.Name,
            TaskType = 1,
            ApiParameter = parameter,
            Interval = DateTimeOffset.Now.AddSeconds(delay).ToString(), // 标识0.1秒后执行
            Status = (int)JobState.开启,
            IntervalDescription = "0.1秒后执行",
            Describe = jobType.FullName,
            TaskExecuteType = "ONE",
            ArgumentTypeName = genericArgument.ToString()
        };
        ArgumentTypeExtension.Add(jobType.Name, genericArgument);
        _taskHandler.Add(task);
    }
}